<?php

namespace App\Dao;

use App\Model\AddressModel;
use Illuminate\Support\Facades\DB;

class AddressDao extends BaseDao
{
    public static function builder_query($params = [])
    {
        $query = AddressModel::query();
        $query->when(checkIsHasField($params,'address_id'),function ($query)use ($params){
            $query->where('address_id',$params['address_id']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        return $query;
    }


    public static function add_address($params = [])
    {
        checkForData(['address_name','address_phone','address_details_str','address_json_data'],['请输入姓名','请输入手机号','请输入详细地址','请输入所需数据'],$params);
        if(self::builder_query()->create($params) === false){
            self::error('创建地址失败');
        }
    }

    public static function update_address($params = [])
    {
        checkForData(['address_id','address_name','address_phone','address_details_str','address_json_data'],['请选择地址','请输入姓名','请输入手机号','请输入详细地址','请输入所需数据'],$params);
        if(self::builder_query(['address_id'=>self::deleteParamId($params,'address_id')])->create(self::filterFields($params,new AddressModel())) === false){
            self::error('创建地址失败');
        }
    }


    public static function delete_address($params = [])
    {
        checkForData(['address_id'],['请选择地址'],$params);
        if(self::builder_query(['address_id'=>self::deleteParamId($params,'address_id')])->delete() === false){
            self::error('删除地址失败');
        }
    }

    public static function lists(array $params)
    {
        return self::builder_query($params)->get()->toArray();
    }

    public static function set_default_address(array $params)
    {
        checkForData(['address_id'],['请选择地址'],$params);
        DB::beginTransaction();
        try {
            self::builder_query([
                'user_id'=>$params['user_id']
            ])->update([
               'is_default'=>0
            ]);
            self::builder_query([
                'address_id'=>$params['address_id']
            ])->update([
                'is_default'=>1
            ]);
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }
}
